<template>
  <view viewport>
    <view class="wrap">
      <view class="card">
        <view class="column_container_title">
          <view class="row_container">
            <image class="title_icon" src="../../static/images/icon_work_time.png"></image>
            <view class="common_title_bold">日报时间</view>
            <view class="date">{{dataIntent.fullDate}} </view>
          </view>
        </view>
        <view class="line"></view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">是否休假</view>
          </view>

          <radio-group class="radio_grop" @change="radioChanged">
            <label class="label">
              <radio color="#54B9CC" style="transform:scale(0.8);color: #54B9CC;" value="0" :checked="isHoliday==0" /> 否
            </label>
            <label class="label">
              <radio color="#54B9CC" style="transform:scale(0.8);color: #54B9CC;" value="1" :checked="isHoliday==1" /> 是
            </label>
          </radio-group>
        </view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">今日完成工作</view>
          </view>
          <view class="text_container">
            <textarea class="text_area" v-model="dataDetail.content" placeholder="请输入工作内容"></textarea>
          </view>
        </view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">明日工作计划</view>
          </view>
          <view class="text_container">
            <textarea class="text_area" v-model="dataDetail.nextDayPlan" placeholder="请输入工作计划"></textarea>
          </view>
        </view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">需要协调与帮助</view>
          </view>
          <view class="text_container">
            <textarea class="text_area" v-model="dataDetail.coordinateHelp" placeholder="请输入"></textarea>
          </view>
        </view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">附件</view>
            <view class="row_container_end" @click="addFile">
              <view class="add_text_plus"> +</view>
              <view class="add_text"> 添加</view>
            </view>
          </view>
          <!--动态表单-->
          <view class="file_container">
            <view class="row_container_between" v-for="(item,index) in fileList" :key="index">
              <image class="file" src="../../static/images/icon_file_img.png" @click="previewFile(item)"></image>
              <image class="add" src="../../static/images/icon_delete_line.png" @click="removeFile(index)"></image>
            </view>
          </view>
        </view>
        <view class="column_container">
          <view class="row_container">
            <view class="line_vertical"></view>
            <view class="common_title">所在位置</view>
          </view>
          <view class="column_container">
            <view class="row_container" @click="chooseLocation">
              <input class="input" v-model="dataDetail.loc" placeholder="请选择位置" />
              <image class="add" src="../../static/images/icon_location.png"></image>
            </view>
          </view>

        </view>

      </view>

    </view>
    <view class="bottom-contianer">
      <button class="button" @click="submit">提交</button>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import type { fileItem } from '@/types/files'
  import { saveClDaily, queryClDailyPage, saveClPlan } from '@/services/plan'
  import { onLoad } from '@dcloudio/uni-app'
  import { useMemberStore } from '@/stores'
  import { reginDetail } from '@/utils/location'
  import { getFileType, uploadFilePromise } from '@/utils/upload'
  import Func from '@/utils/func'

  const userInfo = useMemberStore().getUserInfo()
  const query = defineProps<{
    data : string
  }>()

  type dataDetail = {
    attachIds : string
    attachUrls : string
    content : string
    nextDayPlan : string
    coordinateHelp : string
    loc : string
    gmtCreate ?: string
    gmtModified ?: string
    dataState ?: string
    dailyId ?: string
    dailyCode ?: string

  }
  const dataDetail = ref<dataDetail>({
    attachIds: '',
    attachUrls: '',
    content: '',
    coordinateHelp: '',
    nextDayPlan: '',
    loc: ''
  })

  //页面参数
  type dataIntent = {
    planCode : string
    dayStatus : number
    fullDate : string
    beginDate : string
    endDate : string

  }
  //页面传入数据
  const dataIntent = ref<dataIntent>({
    planCode: '',
    dayStatus: -1,
    fullDate: '',
    beginDate: '',
    endDate: ''
  })
  //附件列表
  const fileList = ref<fileItem[]>([])

  // 是否休假（0：否，1：是）
  const isHoliday = ref(0)

  //单选框事件
  const radioChanged = (e : any) => {
    isHoliday.value = e.detail.value
  }

  function addFile() {

    uni.chooseImage({
      count: 1,
      secret: false,
      position: 'back',
      sourceType: ['camera', 'album'],
      success: async (res : any) => {
        console.log('选择的文件列表:', res.tempFiles[0].path);
        // res.tempFiles 结构： [{ path: '临时路径', name: '文件名', size: 文件大小, type: '文件类型' }]
        const result : any = await uploadFilePromise(res.tempFiles[0].path)
        console.log(result)
        fileList.value.push({
          url: result.url,
          fileId: result.fileId
        })
      },
      fail: (err) => {
        console.error('选择文件失败:', err);
      }
    });
  }

  onLoad(() => {
    dataIntent.value = JSON.parse(query.data)
    console.log(dataIntent.value)
    getLocation()
    //获取数据
    queryClDailyPage({

      userCode: userInfo?.userCode,
      planCode: dataIntent.value.planCode,
      reportDate: dataIntent.value.fullDate
    }).then((res : any) => {
      console.log(res)
      if (res && res.list && res.list.length > 0) {
        dataDetail.value = res.list[0]
        if (dataDetail.value.attachIds) {

          const ids = dataDetail.value.attachIds.split(',')
          const urls = dataDetail.value.attachUrls.split(',')
          fileList.value = []
          ids.forEach((id, idnex) => {
            fileList.value.push({
              url: urls[idnex],
              fileId: id
            })
          })
        }
      }
    })
  })
  //删除
  const removeFile = (index : number) => {
    fileList.value.splice(index, 1)
  }


  //预览
  const previewFile = (item : any) => {
    console.log(item)
    uni.navigateTo({
      url: `/pagesMember/mediaPreview/mediaPreview?data=${JSON.stringify({
        fileCtype: getFileType(item.url),
        fileUrl: item.url,
        attachId: ''
      })}`
    })
  }
  function getLocation() {
    uni.getLocation({
      type: 'gcj02',
      // isHighAccuracy: true,
      success: (res) => {

        console.log('当前位置：', res)

        // 获取当前位置的中文描述
        reginDetail(res.longitude, res.latitude).then((res:any) => {
          console.log(res)
           dataDetail.value.loc = res.address
        })
      },
      fail: (err) => {
        console.error('获取位置失败：', err)

        uni.showToast({ title: '获取位置失败', icon: 'none' })
      },
    })
  }


  //选择地址
  const chooseLocation = () => {
    console.log('selectCity')
    uni.chooseLocation({
      success: function (res) {
        console.log('selectCity', res)
        dataDetail.value.loc = res.address
        reginDetail(res.longitude, res.latitude).then(res => {
          console.log(res)
        })
      },
    })
  }
  //提交
  const submit = () => {
    if (Func.isEmpty(dataDetail.value.content) && isHoliday.value == 0) {
      uni.showToast({
        title: '请输入工作内容',
        icon: 'none'
      })
      return
    }
    //没有周计划需要先生成一个
    if (Func.isEmpty(dataIntent.value.planCode)) {
      saveClPlan({
        userCode: userInfo?.userCode,
        weekWorkPlan: '',
        coordinateHelp: '',
        attachIds: '',
        beginDate: dataIntent.value.beginDate,
        endDate: dataIntent.value.endDate
      }).then((res : any) => {
        console.log(res)
        if (res.success) {
          dataIntent.value.planCode = res.dataObj
          saveDayPlan()
        } else {
          uni.showToast({
            title: '生成周计划失败',
            icon: 'none'
          })
        }
      })
      return
    }
    saveDayPlan()


  }
  //提交周计划
  const saveDayPlan = () => {
    var attachIds = fileList.value.map(item => (item.url))
    var data : any = {

      userCode: userInfo?.userCode,
      reportDate: dataIntent.value.fullDate,
      content: dataDetail.value.content,
      nextDayPlan: dataDetail.value.nextDayPlan,
      coordinateHelp: dataDetail.value.coordinateHelp,
      loc: dataDetail.value.loc,
      planCode: dataIntent.value.planCode,
      isHoliday: isHoliday.value,
      attachIds: attachIds.join(',')
    }
    if (!Func.isEmpty(dataDetail.value.dailyId)) {
      data.dailyId = dataDetail.value.dailyId
    }
    console.log(data)
    saveClDaily(data).then((res : any) => {
      console.log(res)
      if (res.success) {
        uni.showToast({
          title: '提交成功',
          icon: 'none'
        })
        uni.$emit('updatePlan')
        uni.navigateBack()
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
</script>

<style lang="scss">
  page {
    background-color: #F9FAFB;
  }

  .viewport {
    display: flex;
  }

  .wrap {
    padding-bottom: 140rpx;
  }

  .card {
    margin: 40rpx 20rpx;
    background: #FFFFFF;
    display: flex;
    padding: 24rpx;
    flex-direction: column;
    // box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(209, 227, 230, 0.58);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .column_container {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
  }

  .column_container_title {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    display: flex;
    flex-direction: column;
  }

  .file_container {
    margin-top: 32rpx;
  }

  .radio_grop {
    margin-top: 30rpx;
  }

  .row_container {
    margin-left: 5rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .row_container_end {
    margin-right: 5rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    flex-grow: 1;
  }

  .row_container_between {
    margin-right: 5rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    flex-grow: 1;
  }

  .input {
    flex-grow: 1;
    color: #888E98;
    font-size: 30rpx;
  }

  .line_vertical {
    width: 8rpx;
    height: 30rpx;
    margin-right: 10rpx;
    background: linear-gradient(180deg, #61D7ED 0%, #54B9CC 100%);
    border-radius: 4rpx 4rpx 4rpx 4rpx;
  }

  .row_container_title {
    font-size: 28rpx;
    color: #1C253A
  }

  .row_container_content {
    font-size: 28rpx;
    margin-left: 15rpx;
    color: #394259
  }

  .add {
    width: 55rpx;
    height: 55rpx;
    // transform: translateX(400px);
    // filter: drop-shadow(#54B9CC -400px 0);
  }

  .label {
    font-size: 28rpx;
    color: #888E98;
    margin-left: 24rpx;
  }

  .title_icon {
    width: 60rpx;
    height: 60rpx;
  }

  .file {
    width: 100rpx;
    height: 100rpx;
  }

  .add_text {
    margin-left: 10rpx;
    height: 44rpx;
    font-size: 30rpx;
    color: #54B9CC;
    line-height: 44rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .add_text_plus {
    margin-left: 15rpx;
    height: 44rpx;
    font-size: 44rpx;
    color: #54B9CC;
    line-height: 44rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .line {
    background-color: #F2F3F5;
    height: 1rpx;
  }

  .row_container_content_red {
    font-size: 28rpx;
    margin-left: 15rpx;
    color: #E02020
  }

  .title_left {
    height: 48rpx;
    font-weight: 500;
    font-size: 32rpx;
    color: #1C253A;
    line-height: 48rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .common_title {
    height: 48rpx;
    line-height: 48rpx;
    font-size: 32rpx;
    color: black;
  }

  .common_title_bold {
    height: 48rpx;
    line-height: 48rpx;
    font-size: 32rpx;
    color: #1C253A;
    font-weight: bold;
  }

  .date {
    margin-left: 20rpx;
    height: 48rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 30rpx;
    color: #888E98;
    line-height: 48rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }


  .bottom-contianer {
    position: fixed;
    bottom: 40rpx;
    width: 100%;
    z-index: 99;
    display: flex;
    flex-direction: row;
  }

  .button {
    width: 80%;
    background-color: #54B9CC;
    color: white;
    font-size: 32rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }



  .text_container {
    background: #FFFFFF;
    height: 140rpx;
    width: 100%;
    padding: 16rpx;
    margin-top: 16rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    border: 1rpx solid #f5f6fB;
    font-size: 30rpx;
    color: #888E98
  }

  .text_area {
    height: 100rpx
  }
</style>
